package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.eneity.Book;
import com.example.demo.eneity.Chapter;
import com.example.demo.eneity.SocksProxy;
import com.example.demo.service.BookService;
import com.example.demo.service.ChapterService;
import com.example.demo.service.SocksProxyService;
import com.example.demo.util.HttpClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@RestController
public class MainController {
    @Autowired
    private BookService bookService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private SocksProxyService socksProxyService;
    @Value("${down.path}")
    private String path;
    private LinkedList<SocksProxy> socksProxyList = new LinkedList<>();

    private static String getSn(int cpIndex){
        String indexStr = cpIndex+"";
        int i1 = 5 - indexStr.length();
        for (int i =0;i<i1;i++){
            indexStr = "0"+indexStr;
        }
        return indexStr;
    }

    @GetMapping("/download")
    public String download(String bookId){
        Book book = bookService.getOne(new LambdaQueryWrapper<Book>().eq(Book::getBookId,bookId));
        if(book!=null){
            List<Chapter> chapterList = chapterService.list(new LambdaQueryWrapper<Chapter>().eq(Chapter::getBookId, bookId));
            for (int i=0;i<chapterList.size();i++){
                Chapter chapter = chapterList.get(i);
                Integer cpIndex = chapter.getCpIndex();
                String mp3Url = chapter.getMp3Url();
                HttpClientUtil.download(mp3Url,path+book.getAudioAuthor()+"/"+book.getBinfo()+"/",book.getBinfo()+"_第"+getSn(cpIndex)+"集.mp3");
            }
        }
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    /**
     * 根据bookId下载章节
     * @param bookId
     * @return
     */
    @GetMapping("/getBookChapter")
    public String getBookChapter(String bookId,String type){
        try {
            Book bookInfo = getBookInfo(bookId);
            for(int i=1;i<=bookInfo.getAllCp();i++){
                Chapter chapter1 = chapterService.getOne(new LambdaQueryWrapper<Chapter>().eq(Chapter::getBookId, bookId).eq(Chapter::getCpIndex, i));
                if(chapter1==null){
                    Document document = Jsoup.connect("https://m.ting55.com/book/"+bookId+"-"+i).get();
                    Element cpElement = document.selectFirst("[name=_cp]");
                    if(socksProxyList.isEmpty()){
                        initSocksProxyList();
                    }
                    SocksProxy socksProxy = socksProxyList.removeFirst();
                    String s = HttpClientUtil.ting55Post("https://ting55.com/glink?bookId="+bookId+"&isPay=0&page=" + cpElement.attr("content"), "https://ting55.com/book/14799-1","c508f410fde0dbf0b4449bc5121fec6b",socksProxy.getHost(),socksProxy.getPort(),socksProxy.getName(),socksProxy.getPass());
                    String ourl = JSON.parseObject(s).getString("ourl");
                    String url = JSON.parseObject(s).getString("url");
                    if(!StringUtils.isEmpty(ourl)){
                        Chapter chapter = new Chapter();
                        chapter.setBookId(bookId);
                        chapter.setCpIndex(i);
                        chapter.setMp3Url(ourl);
                        chapterService.save(chapter);
                    }
                    if(!StringUtils.isEmpty(url)){
                        Chapter chapter = new Chapter();
                        chapter.setBookId(bookId);
                        chapter.setCpIndex(i);
                        chapter.setMp3Url(url);
                        chapterService.save(chapter);
                        if("1".equals(type)){
                            HttpClientUtil.download(url,path+bookInfo.getAudioAuthor()+"/"+bookInfo.getBinfo()+"/",bookInfo.getBinfo()+"_第"+getSn(i)+"集.mp3");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    private void initSocksProxyList(){
        socksProxyList.addAll(socksProxyService.list());
    }
    private Book getBookInfo(String bookId){
        Book book = bookService.getOne(new LambdaQueryWrapper<Book>().eq(Book::getBookId, bookId));
        if(book==null){
            book = new Book();
            try {
                Document document = Jsoup.connect("https://ting55.com/book/"+bookId).get();
                String bimg = "https:"+document.selectFirst(".bimg").selectFirst("img").attr("src").replaceAll("!300","");
                String binfo = document.selectFirst(".binfo").select("h1").eq(0).text().trim().replaceAll("有声小说","");
                String type = document.selectFirst(".binfo").select("p").eq(0).text().trim().replaceAll("类别：","");
                String author = document.selectFirst(".binfo").select("p").eq(1).text().trim().replaceAll("作者：","");
                String audioAuthor = document.selectFirst(".binfo").select("p").eq(2).text().trim().replaceAll("播音：","");
                String status = document.selectFirst(".binfo").select("p").eq(3).text().trim().replaceAll("状态：","");
                String time = document.selectFirst(".binfo").select("p").eq(4).text().trim().replaceAll("时间：","");
                String intro = document.selectFirst(".intro").selectFirst("p").text().trim();
                int allCp = document.selectFirst(".plist").selectFirst("ul").select("li").size();
                book.setAllCp(allCp);
                book.setAudioAuthor(audioAuthor);
                book.setAuthor(author);
                book.setBimg(bimg);
                book.setBinfo(binfo);
                book.setBookId(bookId);
                book.setIntro(intro);
                book.setStatus(status);
                book.setTime(time);
                book.setType(type);
                bookService.save(book);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return book;
    }

    @GetMapping("/iiss")
    public void iiss(){
        String aas="106.54.27.185︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.54.72.227︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.54.72.135︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.54.72.245︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "49.234.147.51︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "49.235.118.245︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "49.235.60.42︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "129.211.74.148︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "49.234.48.211︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "49.235.188.29︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.54.148.116︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴2︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.54.148.222︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "182.254.205.231︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.43.239︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.197.211︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.63.253︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.43.243︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.52.8.12︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.43.169︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.195.143︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.197.147︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.196.163︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.43.199︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A\n" +
                "106.53.62.63︴12355︴SOCKS5︴shenwu︴shenwu︴上海上海市︴电信︴25︴3︴2020-10-01 14:10:25︴ALLMD5︴启用︴N/A";
        String[] strings = aas.split("\\n");
        for (String s: strings) {
            String[] strings1 = s.split("︴");
            SocksProxy socksProxy = new SocksProxy();
            socksProxy.setHost(strings1[0]);
            socksProxy.setPort(Integer.parseInt(strings1[1]));
            socksProxy.setName(strings1[3]);
            socksProxy.setPass(strings1[4]);
            socksProxyService.save(socksProxy);
        }
    }
}
